package com.icinfo.cloud.provider.punish.fastcase.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.core.config.CfRedisRepository;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.config.ThreadPoolConfig;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.DocumentKindEnum;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.common.utils.*;
import com.icinfo.cloud.provider.punish.approval.dto.ApprovalAgreeAuditDto;
import com.icinfo.cloud.provider.punish.approval.dto.ApprovalGeneralSubmitDto;
import com.icinfo.cloud.provider.punish.approval.service.ICaseApprovalWaitRecordService;
import com.icinfo.cloud.provider.punish.approval.vo.NextAuditUserVo;
import com.icinfo.cloud.provider.punish.common.documentdataload.dto.CaseDocumentRecordCommonQueryDto;
import com.icinfo.cloud.provider.punish.common.documentdataload.dto.CasePartiesQueryDto;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.FillAndConvertToPdfRequest;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.StageDocCommonHtmlRequest;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.StageDocCommonOperateSaveDto;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentRecordStatusEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentStatusEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.service.IStageDocCommonOperateService;
import com.icinfo.cloud.provider.punish.common.documentoperate.vo.DocumentCommonFormDataVo;
import com.icinfo.cloud.provider.punish.config.dto.ConfigDictionaryInfoQueryDto;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.model.ConfigDictionaryInfo;
import com.icinfo.cloud.provider.punish.config.model.SysDepartParam;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.config.service.IConfigDictionaryInfoService;
import com.icinfo.cloud.provider.punish.config.service.ISysDepartParamService;
import com.icinfo.cloud.provider.punish.fastcase.dto.FastCaseAutoEndSaveDto;
import com.icinfo.cloud.provider.punish.fastcase.service.IFastCaseDocumentRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseAttachmentInfoQueryDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.CaseDocumentRecordDelRequest;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.AttachmentTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseStageEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.HandlePersonTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartyTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseDocumentRecordHisMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseDocumentRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseDocumentRecordHis;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseHandlePersonRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainDetailInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.*;
import com.icinfo.cloud.provider.punish.ucase.payment.dto.CasePaymentItemDetailQueryDto;
import com.icinfo.cloud.provider.punish.ucase.payment.dto.CasePaymentMainRecordQueryDto;
import com.icinfo.cloud.provider.punish.ucase.payment.service.ICasePaymentItemDetailService;
import com.icinfo.cloud.provider.punish.ucase.payment.service.ICasePaymentMainRecordService;
import com.icinfo.cloud.provider.punish.ucase.payment.service.ICasePaymentResultRecordService;
import com.icinfo.cloud.provider.punish.ucase.payment.vo.CasePaymentItemDetailVo;
import com.icinfo.cloud.provider.punish.ucase.payment.vo.CasePaymentMainRecordVo;
import com.icinfo.cloud.provider.punish.ucase.payment.vo.CasePaymentResultRecordVo;
import com.icinfo.cloud.provider.punish.ucase.punishinform.dto.FastCaseAddInfoDto;
import com.icinfo.cloud.workflow.config.model.ConfigWorkFlowDetailInfo;
import com.icinfo.cloud.workflow.config.model.ConfigWorkFlowDocument;
import com.icinfo.cloud.workflow.config.service.IConfigWorkFlowDetailInfoService;
import com.icinfo.cloud.workflow.config.service.IConfigWorkFlowDocumentService;
import com.icinfo.cloud.workflow.work.service.IWorkFlowRollInfoCustomService;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.exception.BusinessException;
import com.icinfo.framework.tools.utils.MapUtils;
import com.icinfo.framework.tools.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

/**
 * @author shishengyao
 * @description
 * @date 2023/4/19
 */
@Service
public class FastCaseDocumentRecordServiceImpl implements IFastCaseDocumentRecordService {
    @Resource
    private ICaseDocumentRecordService caseDocumentRecordService;
    @Resource
    private IStageDocCommonOperateService stageDocCommonOperateService;
    @Resource
    private IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;
    @Resource
    private ICaseMainInfoService caseMainInfoService;
    @Resource
    private ICaseHandlePersonRecordService caseHandlePersonRecordService;
    @Resource
    private CaseDocumentRecordHisMapper caseDocumentRecordHisMapper;
    @Resource
    private CaseDocumentRecordMapper caseDocumentRecordMapper;
    @Resource
    private ICasePartiesRecordService casePartiesRecordService;
    @Resource
    private ICaseMainDetailInfoService caseMainDetailInfoService;
    @Resource
    private IConfigWorkFlowDocumentService configWorkFlowDocumentService;
    @Resource
    private IConfigWorkFlowDetailInfoService configWorkFlowDetailInfoService;
    @Resource
    private ICaseReasonMainRecordService caseReasonMainRecordService;
    @Resource
    private IWorkFlowRollInfoCustomService workFlowRollInfoCustomService;
    @Resource
    private IConfigDictionaryInfoService configDictionaryInfoService;
    @Resource
    private ICaseApprovalWaitRecordService caseApprovalWaitRecordService;
    @Resource
    private CfRedisRepository cfRedisRepository;
    @Resource
    private ICasePaymentItemDetailService casePaymentItemDetailService;
    @Resource
    private ICasePaymentMainRecordService casePaymentMainRecordService;
    @Resource
    private ICaseAppendixRecordService caseAppendixRecordService;
    @Resource
    private ICasePaymentResultRecordService casePaymentResultRecordService;
    @Resource
    private ISysDepartParamService sysDepartParamService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveFastCaseRegisterDocument(String caseId, FastCaseAddInfoDto fastCaseAddInfoDto) {
        UserDTO userInfo = UserUtil.getUserInfo();
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoService.getCaseMainDetailByCaseId(caseId);
        String investConclusion = caseMainDetailInfo.getInvestConclusion();
        Map annoyMap = new HashMap();
        int count = 0;
        LocalDateTime documentCreateTime = LocalDateTime.now();
        CountDownLatch countDownLatch = new CountDownLatch(Constant.INTEGER_4);
        for (int i = 0; i < Constant.INTEGER_4; i++) {
            int finalI = i;
            ThreadPoolConfig.FAST_CASE_REGISTER_DOCUMENT_POOL.execute(() -> {
                try {
                    switch (finalI) {
                        case 0:
                            //立案审批表
                            ConfigBusiParamDocumentInfo caseRegisterConfig = configBusiParamDocumentInfoService.getFastCaseDocumentInfoByDocumentKindCode(caseMainInfo.getBusiParamId(), DocumentKindEnum.DOC_KIND_LASPB.getCode(), Constant.STRING_1);
                            int docCount0 = saveFastCaseRegisterDocument(caseMainInfo, caseRegisterConfig, userInfo, fastCaseAddInfoDto, caseMainDetailInfo, documentCreateTime);
                            annoyMap.put(CaseStageEnum.CASE_REGISTER.getCode(), caseRegisterConfig.getDocumentCatalogCode());
                            annoyMap.put("doc0", docCount0);
                            break;
                        case 1:
                            //终结报告
                            ConfigBusiParamDocumentInfo zjbgConfig = configBusiParamDocumentInfoService.getFastCaseDocumentInfoByDocumentKindCode(caseMainInfo.getBusiParamId(), DocumentKindEnum.DOC_KIND_ZJBG.getCode(), Constant.STRING_1);
                            int docCount1 = saveFastCaseRegisterDocument(caseMainInfo, zjbgConfig, userInfo, fastCaseAddInfoDto, caseMainDetailInfo, documentCreateTime.plusMinutes(1));
                            annoyMap.put(CaseStageEnum.INVESTIGATION.getCode(), zjbgConfig.getDocumentCatalogCode());
                            annoyMap.put("doc1", docCount1);
                            break;
                        case 2:
                            //告知审批表
                            ConfigBusiParamDocumentInfo gzspbConfig = null;
                            ConfigBusiParamDocumentInfo cfgzspbConfig = configBusiParamDocumentInfoService.getFastCaseDocumentInfoByDocumentKindCode(caseMainInfo.getBusiParamId(), DocumentKindEnum.DOC_KIND_CFGZSPB.getCode(), Constant.STRING_1);
                            ConfigBusiParamDocumentInfo bygzspbConfig = configBusiParamDocumentInfoService.getFastCaseDocumentInfoByDocumentKindCode(caseMainInfo.getBusiParamId(), DocumentKindEnum.DOC_KIND_DK1BYCFGZSPB.getCode(), Constant.STRING_1);
                            CaseDocumentRecordDelRequest caseDocumentRecordDelRequest = new CaseDocumentRecordDelRequest();
                            caseDocumentRecordDelRequest.setCaseId(caseId);
                            if (Constant.STRING_1.equals(investConclusion)) {
                                caseDocumentRecordDelRequest.setDocumentCatalogCode(bygzspbConfig.getDocumentCatalogCode());
                                caseDocumentRecordService.delCaseDocumentRecordInfo(caseDocumentRecordDelRequest);
                                gzspbConfig = cfgzspbConfig;
                            } else {
                                //不予处罚
                                caseDocumentRecordDelRequest.setDocumentCatalogCode(cfgzspbConfig.getDocumentCatalogCode());
                                caseDocumentRecordService.delCaseDocumentRecordInfo(caseDocumentRecordDelRequest);
                                gzspbConfig = bygzspbConfig;
                            }
                            int docCount2 = saveFastCaseRegisterDocument(caseMainInfo, gzspbConfig, userInfo, fastCaseAddInfoDto, caseMainDetailInfo, documentCreateTime.plusMinutes(2));
                            annoyMap.put(CaseStageEnum.PUNISH_INFORM.getCode(), gzspbConfig.getDocumentCatalogCode());
                            annoyMap.put("doc2", docCount2);
                            break;
                        case 3:
                            // 告知书
                            ConfigBusiParamDocumentInfo gzsConfig = null;
                            ConfigBusiParamDocumentInfo cfgzsConfig = configBusiParamDocumentInfoService.getFastCaseDocumentInfoByDocumentKindCode(caseMainInfo.getBusiParamId(), DocumentKindEnum.DOC_KIND_CFGZS.getCode(), Constant.STRING_1);
                            ConfigBusiParamDocumentInfo bycfgzsConfig = configBusiParamDocumentInfoService.getFastCaseDocumentInfoByDocumentKindCode(caseMainInfo.getBusiParamId(), DocumentKindEnum.DOC_KIND_DK2BYXZCFGZS.getCode(), Constant.STRING_1);
                            CaseDocumentRecordDelRequest caseDocumentRecordDelRequest2 = new CaseDocumentRecordDelRequest();
                            caseDocumentRecordDelRequest2.setCaseId(caseId);
                            if (Constant.STRING_1.equals(investConclusion)) {
                                caseDocumentRecordDelRequest2.setDocumentCatalogCode(bycfgzsConfig.getDocumentCatalogCode());
                                caseDocumentRecordService.delCaseDocumentRecordInfo(caseDocumentRecordDelRequest2);
                                gzsConfig = cfgzsConfig;
                            } else {
                                //不予处罚
                                caseDocumentRecordDelRequest2.setDocumentCatalogCode(cfgzsConfig.getDocumentCatalogCode());
                                caseDocumentRecordService.delCaseDocumentRecordInfo(caseDocumentRecordDelRequest2);
                                gzsConfig = bycfgzsConfig;
                            }
                            int docCount3 = saveFastCaseRegisterDocument(caseMainInfo, gzsConfig, userInfo, fastCaseAddInfoDto, caseMainDetailInfo, documentCreateTime.plusMinutes(2));
                            annoyMap.put("doc3", docCount3);
                            break;
                        default:
                            break;
                    }
                } catch (Exception e) {
                    throw new BusinessException("立案审批表生成失败");
                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        try {
            //等待所有任务都完成
            countDownLatch.await();
            for (int i = 0; i < 4; i++) {
                int num = ObjectUtil.isEmpty(annoyMap.get("doc" + i)) ? 0 : Integer.decode(annoyMap.get("doc" + i).toString());
                count = count + num;
            }
            if (count != Constant.INTEGER_4) {
                throw new BusinessException("合并文书生成失败");
            }
        } catch (InterruptedException e) {
            throw new BusinessException("合并文书生成失败");
        }
        annoyMap.put("investConclusion", investConclusion);
        //滚动到处罚告知环节
        workFlowRollInfoCustomService.doDealWorkFlowRollPunishInformStage(caseId, casePartiesRecordService.getPartIdsByCaseId(caseId), annoyMap, CaseStageEnum.PUNISH_INFORM.getCode());
        return count;
    }

    @Override
    public List<CaseStageLinkRelateDocumentVo> getFastCaseMergeDocumentBeforeInform(String caseId) {
        CaseMainInfoVo caseMainInfoVo = caseMainInfoService.getCaseMainInfo(caseId);
        String workFlowVersion = caseMainInfoVo.getCaseFlowVersion();
        String workFlowCode = caseMainInfoVo.getCaseFlowCode();
        List<ConfigWorkFlowDocument> list = configWorkFlowDocumentService.getConfigWorkFlowDocumentMatchedListByFlowCode(workFlowCode, workFlowVersion);
        Map<String, String> matchMapCatalogCode = new HashMap<>(20);
        Map<String, String> matchMapIsMatchDocument = new HashMap<>(20);
        list.forEach(e -> {
            matchMapCatalogCode.put(e.getDocumentCatalogCode(), e.getMatchedDocumentCatalogCode());
            matchMapIsMatchDocument.put(e.getDocumentCatalogCode(), e.getIsMatchDocument());
        });
        //案件阶段查询
        ConfigDictionaryInfoQueryDto dto = new ConfigDictionaryInfoQueryDto();
        dto.setIsEffective(Constant.STRING_1);
        dto.setDicFieldCode(Constant.STRING_CASE_STAGE);

        //关联文书
        CaseStageLinkRelateDocumentQueryDto query = new CaseStageLinkRelateDocumentQueryDto();
        List<String> documentKindCodeList = Arrays.asList(DocumentKindEnum.DOC_KIND_LASPB.getCode(),
                DocumentKindEnum.DOC_KIND_ZJBG.getCode(),
                DocumentKindEnum.DOC_KIND_CFGZSPB.getCode(),
                DocumentKindEnum.DOC_KIND_CFGZS.getCode());
        query.setCaseId(caseId);
        //查询正常和草稿文书
        query.setDocumentRecordStatus(Constant.STRING_1_2);
        query.setDocumentKindCodeList(documentKindCodeList);
        return caseDocumentRecordService.getCaseStageLinkRelateDocumentInfo(query);
    }

    @Override
    public void saveFastCaseAutoEndDocument(FastCaseAutoEndSaveDto saveDto) {
        String caseId = saveDto.getCaseId();
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(saveDto.getCaseId());
        CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoService.getCaseMainDetailByCaseId(saveDto.getCaseId());
        //获取办案人员
        List<CaseHandlePersonRecord> caseHandlePersonRecordList = caseHandlePersonRecordService.getCaseHandlePersonRecordList(caseId);
        // 生成自动执行情况记录表
        generateExecuteConditionAutomaticRecord(saveDto, caseMainDetailInfo, caseHandlePersonRecordList);
        //生成结案报告
        ConfigBusiParamDocumentInfo jabgConfig = configBusiParamDocumentInfoService.getFastCaseDocumentInfoByDocumentKindCode(caseMainInfo.getBusiParamId(), DocumentKindEnum.DOC_KIND_JABG.getCode(), Constant.STRING_1);
        generateEndReportDocument(caseMainInfo, caseMainDetailInfo, caseHandlePersonRecordList, saveDto, jabgConfig);
        //结案报告自动审批
        NextAuditUserVo nextAutoAuditUserVo = caseApprovalWaitRecordService.getNextAutoAuditUserVo(caseId, jabgConfig.getDocumentCatalogCode());
        //下一环节自动审批人不为空则走自动审批
        if (ObjectUtil.isNotEmpty(nextAutoAuditUserVo)) {
            ApprovalGeneralSubmitDto dto = new ApprovalGeneralSubmitDto();
            dto.setCaseId(caseId);
            dto.setDocumentCatalogCode(jabgConfig.getDocumentCatalogCode());
            dto.setIsAutoApproval(nextAutoAuditUserVo.getIsAutoApproval());
            dto.setNextHandler(nextAutoAuditUserVo.getUserId());
            dto.setOpinion("申请结案");
            cfRedisRepository.set("IS_APPROVAL_AUTO_PASS" + dto.getCaseId(), "false");
            Map<String, Object> result = caseApprovalWaitRecordService.documentGeneralSubmitAuto(dto.getCaseId(), dto.getDocumentCatalogCode(), dto.getNextHandler(), dto.getOpinion(), dto.getPartyId(), dto.getCaseAssistId(), dto.getIsAutoApproval(), dto.getAutoTime());
            String closeSignal = MapUtils.getString(result, "closeSignal", "");
            if (!"CLOSE-TRIGGER-APPROVAL".equals(closeSignal)) {
                Result.error("操作失败！");
            }
            ApprovalAgreeAuditDto approvalAgreeAuditDto = caseApprovalWaitRecordService.getApprovalAgreeAuditDto(dto);
            for (int i = 0; i < 4; i++) {
                //如果下个环节是自动审批
                if (Constant.STRING_1.equals(approvalAgreeAuditDto.getIsAutoApproval())) {
                    Long autoTime = Long.valueOf(approvalAgreeAuditDto.getAutoTime());
                    if (autoTime > 2) {
                        autoTime = autoTime - 2;
                    }
                    try {
                        Thread.sleep(autoTime * 1000);
                        //Thread.sleep(autoTime);
                        Map<String, Object> agreeResult = caseApprovalWaitRecordService.doAgreeAuditAuto(approvalAgreeAuditDto);
                        closeSignal = MapUtils.getString(agreeResult, "closeSignal", "");
                        result.put("closeSignal", "CLOSE-TRIGGER-APPROVAL-PASS");
                        if ("CLOSE-TRIGGER-APPROVAL-PASS".equals(closeSignal)) {
                            cfRedisRepository.set("IS_APPROVAL_AUTO_PASS" + dto.getCaseId(), "true");
                            break;
                        }
                        String nowHandler = approvalAgreeAuditDto.getNextHandler();
                        approvalAgreeAuditDto = caseApprovalWaitRecordService.getApprovalAgreeAuditDto(dto);
                        approvalAgreeAuditDto.setNowHandler(nowHandler);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    cfRedisRepository.set("IS_APPROVAL_AUTO_PASS" + dto.getCaseId(), "true");
                    break;
                }
            }
        }
    }


    /**
     * 描述：组装快速办理立案登记文书
     *
     * @param caseMainInfo                案例主要信息
     * @param configBusiParamDocumentInfo 配置商业参数文档信息
     * @param userInfo                    用户信息
     * @param fastCaseAddInfoDto          快速添加信息dto
     * @author shishengyao
     * @date 2023/05/05
     */
    public int saveFastCaseRegisterDocument(CaseMainInfoVo caseMainInfo, ConfigBusiParamDocumentInfo configBusiParamDocumentInfo, UserDTO userInfo, FastCaseAddInfoDto fastCaseAddInfoDto, CaseMainDetailInfo caseMainDetailInfo, LocalDateTime documentCreateTime) {
        String caseId = caseMainInfo.getId();
        //配置表
        String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
        String templateCode = configBusiParamDocumentInfo.getFastTemplatePersonCode();
        String documentCatalogCode = configBusiParamDocumentInfo.getDocumentCatalogCode();
        //当事人信息
        List<CasePartiesRecordVo> casePartiesInfo = casePartiesRecordService.getCasePartiesInfo(caseId);
        String partyId = casePartiesInfo.stream().map(CasePartiesRecordVo::getPartyId).collect(Collectors.joining(","));

        // 1、查询是否有文书
        CaseDocumentRecord oldRecordInfo = caseDocumentRecordService.getCaseDocumentRecord(caseId, documentCatalogCode);
        Map<String, Object> paramMap;
        //存在历史数据，更新历史数据
        if (ObjectUtil.isNotEmpty(oldRecordInfo) && ObjectUtil.isNotEmpty(oldRecordInfo.getDocumentContent())) {
            String documentContent = oldRecordInfo.getDocumentContent();
            paramMap = JSON.parseObject(documentContent);
            assembleDocumentModifyParam(caseId, documentKindCode, paramMap, fastCaseAddInfoDto, caseMainDetailInfo);
        } else {
            StageDocCommonHtmlRequest htmlRequest = new StageDocCommonHtmlRequest();
            htmlRequest.setCaseId(caseId);
            htmlRequest.setDocumentCatalogCode(configBusiParamDocumentInfo.getDocumentCatalogCode());
            DocumentCommonFormDataVo dataVo = stageDocCommonOperateService.getCommonDocumentFormData(htmlRequest);
            paramMap = dataVo.getDataMap();
            //组装初始化文书参数
            assembleDocumentModifyParam(caseId, documentKindCode, paramMap, fastCaseAddInfoDto, caseMainDetailInfo);
            //组装变更参数
        }
        //3、生成文书
        FillAndConvertToPdfRequest pdfRequest = new FillAndConvertToPdfRequest();
        pdfRequest.setTemplateCode(templateCode);
        pdfRequest.setParamMap(paramMap);
        Map<String, String> pdfUrlMap = stageDocCommonOperateService.getConvertedPdfUrl(pdfRequest);
        String pdfUrl = pdfUrlMap.get("fileUrl");
        //4、
        CaseDocumentRecord caseDocumentRecord = new CaseDocumentRecord();
        caseDocumentRecord.setDocumentRecordStatus(DocumentRecordStatusEnum.NORMAL.getCode());
        caseDocumentRecord.setDocumentUrl(pdfUrl);
        caseDocumentRecord.setDocumentContent(JSONObject.toJSONString(paramMap));
        caseDocumentRecord.setDocumentTemplateCode(templateCode);
        caseDocumentRecord.setDocumentUrlAfterSeal("");
        //生成默认待提交状态
        if ("1".equals(configBusiParamDocumentInfo.getIsApprove())) {
            caseDocumentRecord.setDocumentApprovalStatus(DocumentStatusEnum.WAIT_TO_SUBMIT.getCode());
            caseDocumentRecord.setDocumentAuditStatus("notSubmit");
        }
        if ("1".equals(configBusiParamDocumentInfo.getIsSend())) {
            caseDocumentRecord.setDocumentSentStatus(DocumentStatusEnum.WAIT_TO_SEND.getCode());
        }
        if (BusinessContextUtil.documentNeedConfirm(configBusiParamDocumentInfo)) {
            caseDocumentRecord.setDocumentSignstampedStatus(DocumentStatusEnum.WAIT_TO_CONFIRM.getCode());
        }
        caseDocumentRecord.setCreateUserName(userInfo.getRealName());
        caseDocumentRecord.setCreateUserId(userInfo.getUserId().toString());
        caseDocumentRecord.setDocumentCatalogCode(documentCatalogCode);
        if (ObjectUtil.isNotEmpty(oldRecordInfo)) {
            //添加历史
            CaseDocumentRecordHis caseDocumentRecordHis = new CaseDocumentRecordHis();
            BeanUtils.copyProperties(oldRecordInfo, caseDocumentRecordHis);
            //增加创建时间设置
            try {
                Date createTime = Date.from(oldRecordInfo.getDocumentCreateTime().atZone(ZoneId.systemDefault()).toInstant());
                caseDocumentRecordHis.setDocumentCreateTime(createTime);
            } catch (Exception e) {
            }
            caseDocumentRecordHis.setId(StringUtils.uuid());
            caseDocumentRecordHis.setRecordId(oldRecordInfo.getId());
            caseDocumentRecordHis.setOp("update");
            caseDocumentRecordHis.setHisCreateTime(new Date());
            caseDocumentRecordHisMapper.insert(caseDocumentRecordHis);

            caseDocumentRecord.setId(oldRecordInfo.getId());
            return caseDocumentRecordMapper.updateByPrimaryKeySelective(caseDocumentRecord);
        } else {
            if (!DocumentKindEnum.DOC_KIND_LASPB.getCode().equals(documentKindCode)) {
                String stageCode = CaseStageEnum.INVESTIGATION.getCode();
                if (Arrays.asList(DocumentKindEnum.DOC_KIND_CFGZSPB.getCode(), DocumentKindEnum.DOC_KIND_CFGZS.getCode(), DocumentKindEnum.DOC_KIND_DK1BYCFGZSPB.getCode(),
                        DocumentKindEnum.DOC_KIND_DK2BYXZCFGZS.getCode()).contains(documentKindCode)) {
                    stageCode = CaseStageEnum.PUNISH_INFORM.getCode();
                }
                //
                caseDocumentRecord.setDocumentCreateTime(documentCreateTime);
                List<ConfigWorkFlowDocument> ConfigWorkFlowDocumentList = configWorkFlowDocumentService.getConfigWorkFlowDocumentByWorkFLowStageCodeAndCatalogCode(caseMainInfo.getCaseFlowCode(), caseMainInfo.getCaseFlowVersion(), stageCode, documentCatalogCode);
                if (ConfigWorkFlowDocumentList.size() > 0) {
                    ConfigWorkFlowDetailInfo configWorkFlowDetailInfo = configWorkFlowDetailInfoService.getConfigWorkFlowDetailInfoByLinkCode(ConfigWorkFlowDocumentList.get(0).getWorkFlowCode(), ConfigWorkFlowDocumentList.get(0).getWorkLinkCode());
                    caseDocumentRecord.setCaseStageName(configWorkFlowDetailInfo.getWorkStageName());
                    caseDocumentRecord.setCaseStageCode(configWorkFlowDetailInfo.getWorkStageCode());
                    caseDocumentRecord.setCaseLinkCode(configWorkFlowDetailInfo.getWorkLinkCode());
                    caseDocumentRecord.setCaseLinkName(configWorkFlowDetailInfo.getWorkLinkName());
                } else {
                    throw new BusinessException("工作流缺失");
                }
            }
            caseDocumentRecord.setPartyId(partyId);
            caseDocumentRecord.setCaseId(caseId);
            caseDocumentRecord.setId(StringUtils.uuid());
            return caseDocumentRecordMapper.insertSelective(caseDocumentRecord);
        }
    }


    /**
     * 描述：组装文书变更参数
     *
     * @param caseId             用例id
     * @param documentKindCode   文件类型代码
     * @param dataMap            数据地图
     * @param fastCaseAddInfoDto 快速添加信息dto
     * @author shishengyao
     * @date 2023/05/04
     */
    public void assembleDocumentModifyParam(String caseId, String documentKindCode, Map<String, Object> dataMap, FastCaseAddInfoDto fastCaseAddInfoDto, CaseMainDetailInfo caseMainDetailInfo) {
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);

        List<CaseHandlePersonRecord> caseHandlePersonRecordList = caseHandlePersonRecordService.getCaseHandlePersonRecordList(caseId);
        String todayStr = DateTimeFormatter.ofPattern("yyyy年M月d日").format(LocalDate.now());

        //办案人员名称
        String handlePersonNames = caseHandlePersonRecordList.stream().map(CaseHandlePersonRecord::getHandlePersonName).collect(Collectors.joining("、"));
        //默认文书创建当天
        String caseRegisterTimeStr = DateTimeFormatter.ofPattern("yyyy年M月d日").format(LocalDateTime.now());
        //违则
        String illegalBasisFormat = "";
        //罚则
        String punishBasis = "";
        String punishBasisFormat = "";
        String illegalDetailFormat = "";
        String punishDetailFormat = "";
        String caseReasonName = "";
        String caseReasonNameSimple = "";
        List<CaseReasonMainRecordVo> caseReasonRecordList = caseReasonMainRecordService.getCaseReasonRecordListByCaseId(caseId);
        if (ObjectUtil.isNotEmpty(caseReasonRecordList)) {
            CaseReasonMainRecordVo caseReasonMainRecordVo = caseReasonRecordList.get(0);
            illegalBasisFormat = caseReasonMainRecordVo.getIllegalBasisFormat();
            punishBasis = caseReasonMainRecordVo.getPunishBasis();
            punishBasisFormat = caseReasonMainRecordVo.getPunishBasisFormat();
            illegalDetailFormat = caseReasonMainRecordVo.getIllegalDetailFormat();
            punishDetailFormat = caseReasonMainRecordVo.getPunishDetailFormat();
            caseReasonName = caseReasonMainRecordVo.getCaseReasonName();
            caseReasonNameSimple = caseReasonMainRecordVo.getCaseReasonNameSimple();
        }
        List<CasePartiesInfoVo> casePartiesInfos = casePartiesRecordService.getCasePartiesInfoVo(caseId, "");
        String partyNames = casePartiesInfos.stream().map(CasePartiesInfoVo::getPartyName).collect(Collectors.joining("、"));

        if (DocumentKindEnum.DOC_KIND_ZJBG.getCode().equals(documentKindCode)) {
            //立案信息修改会变更调查终结报告字段
            //案件名称, 调查开始时间, 调查结束时间, 案发经过, 当事人基本情况
            dataMap.put("AJDCZJBG_AY", caseMainInfo.getCaseName());
            dataMap.put("AJDCZJBG_DCKSSJ", fastCaseAddInfoDto.getInvestigationStartDate());
            dataMap.put("AJDCZJBG_DCJSSJ", fastCaseAddInfoDto.getInvestigationEndDate());
            dataMap.put("AJDCZJBG_AFJG", fastCaseAddInfoDto.getCaseHappenProcess());
            dataMap.put("AJDCZJBG_WFSS", fastCaseAddInfoDto.getIllegalFact());
            //相关证据
            dataMap.put("AJDCZJBG_XGZJ", caseMainDetailInfo.getRelateEvidence());
            //处罚建议
            dataMap.put("AJDCZJBG_CFJY", fastCaseAddInfoDto.getPunishContent());
            if (Constant.STRING_2.equals(caseMainDetailInfo.getInvestConclusion())) {
                dataMap.put("AJDCZJBG_CFJY", "不予处罚");
            }
            dataMap.put("AJDCZJBG_DSRYJ", fastCaseAddInfoDto.getPartyOpinion());
            dataMap.put("sealDate", todayStr);

            //当事人基本情况
            String partyBasicInfo = null;
            if (ObjectUtil.isNotEmpty(casePartiesInfos)) {
                CasePartiesInfoVo casePartiesInfoVo = casePartiesInfos.get(0);
                if (PartyTypeEnum.PERSON.getCode().equals(casePartiesInfoVo.getPartyType())) {
                    partyBasicInfo = "姓名：" + casePartiesInfoVo.getPartyName()
                            + "，性别：" + casePartiesInfoVo.getSex()
                            + "，出生日期：" + casePartiesInfoVo.getBirth()
                            + "，公民身份号码：" + casePartiesInfoVo.getPartyIdentityCode()
                            + "，住所：" + casePartiesInfoVo.getAddress();
                } else {
                    partyBasicInfo = "企业名称：" + casePartiesInfoVo.getPartyName()
                            + "，统一社会信用代码：" + casePartiesInfoVo.getPartyIdentityCode()
                            + "，法定代表人：" + casePartiesInfoVo.getLegalName()
                            + "，住所：" + casePartiesInfoVo.getAddress();
                }
            }
            dataMap.put("AJDCZJBG_DSRJBQK", partyBasicInfo);
            //违则
            dataMap.put("AJDCZJBG_WZ", illegalBasisFormat);
            //罚则
            dataMap.put("AJDCZJBG_FZ", punishBasis);
            //案由
            dataMap.put("AJDCZJBG_WFJB", caseReasonNameSimple);
            //调查开始时间
            dataMap.put("AJDCZJBG_DCKSSJ", DateUtil.parseDateStrToString(fastCaseAddInfoDto.getInvestigationStartDate(), "yyyy年M月d日"));
            //调查结束时间
            dataMap.put("AJDCZJBG_DCJSSJ", DateUtil.parseDateStrToString(fastCaseAddInfoDto.getInvestigationEndDate(), "yyyy年M月d日"));
            //调查人
            dataMap.put("AJDCZJBG_DCR", handlePersonNames);
            //案发经过

            String dataGenerateRule = "，${casePartyNames}在${caseHappenAddressDetail}实施${caseReason}的违法行为。执法人员对现场进行拍照勘察、取证。被勘验人对现场勘验情况无异议。本案于${caseRegisterTime}立案，对";
            caseMainDetailInfo.setCaseRegisterTime(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年M月d日")));
            caseMainDetailInfo.setCaseReason(caseReasonNameSimple);
            String caseHappenProcess = ParseTextUtil.parseText(dataGenerateRule, BaseUtil.javaToMap(caseMainDetailInfo));
            String investigationEndDate = DateUtil.parseDateStrToString(fastCaseAddInfoDto.getInvestigationEndDate(), "yyyy年M月d日");
            String caseHappenTime = caseMainDetailInfo.getCaseHappenTime().format(DateTimeFormatter.ofPattern("yyyy年M月d日"));
            dataMap.put("AJDCZJBG_AFJG", caseHappenTime + caseHappenProcess + partyNames + "进行了调查询问。并于" + investigationEndDate + "结束案件调查。");

            //办案人员信息
            dataMap = dealAssembleDocumentHandlePerson(caseHandlePersonRecordList, dataMap);

        } else if (DocumentKindEnum.DOC_KIND_CFGZSPB.getCode().equals(documentKindCode)
                || DocumentKindEnum.DOC_KIND_DK1BYCFGZSPB.getCode().equals(documentKindCode)) {
            //处罚告知审批表或不予处罚告知审批表
            //案件名称
            dataMap.put("caseName", caseMainInfo.getCaseName());
            //案发地
            dataMap.put("caseHappenAddress", caseMainDetailInfo.getCaseHappenAddressDetail());
            //案发地
            dataMap.put("caseHappenTime", caseMainDetailInfo.getCaseHappenTime().format(DateTimeFormatter.ofPattern("yyyy年M月d日")));
            //具体违法事实
            dataMap.put("XZCFGZSPB_JTWFSS", fastCaseAddInfoDto.getIllegalFact());
            //相关证据
            dataMap.put("XZCFGZSPB_XGZJ", caseMainDetailInfo.getRelateEvidence());
            //处罚依据
            dataMap.put("XZCFGZSPB_CFYJ", punishBasisFormat);

            if (DocumentKindEnum.DOC_KIND_DK1BYCFGZSPB.getCode().equals(documentKindCode)) {
                //不予处罚原因
                ConfigDictionaryInfo configDictionaryInfo = configDictionaryInfoService.getConfigDictionaryByFieldCodeAndDicCode("NOT_GIVE_PUNISH_REASON", fastCaseAddInfoDto.getNotGivePunishReason());
                if (ObjectUtil.isNotEmpty(configDictionaryInfo)) {
                    dataMap.put("noPunishReason", configDictionaryInfo.getDicName());
                }
                //不予处罚说明
                dataMap.put("noPunishReasonDesc", fastCaseAddInfoDto.getNotGivePunishDetail());
            }
            //办案人员信息
            dataMap = dealAssembleDocumentHandlePerson(caseHandlePersonRecordList, dataMap);
            //当事人信息
            dataMap = dealAssembleDocumentPersonInfo(caseId, dataMap);

        } else if (DocumentKindEnum.DOC_KIND_CFGZS.getCode().equals(documentKindCode)) {

            dataMap.put("CFGZS__LARQ", caseRegisterTimeStr);
            //当事人
            dataMap.put("CFGZS_DSRMC", partyNames);
            //案由
            dataMap.put("CFGZS_AY", caseReasonNameSimple);
            //联系人
            dataMap.put("XZCFSXGZS_LXR", handlePersonNames);
            //违法事实
            dataMap.put("XZCFSXGZS_WFSS", fastCaseAddInfoDto.getIllegalFact());
            ////违则
            dataMap.put("CFGZS_WZ", illegalBasisFormat);
            //证据材料
            dataMap.put("CFGZS_ZJCL", caseMainDetailInfo.getRelateEvidence());
            //罚则
            dataMap.put("CFGZS_AYFZ", punishBasisFormat);
            //责令内容
            dataMap.put("chargeContent", "");
            //处罚建议
            dataMap.put("XZCFSXGZS_CFJY", fastCaseAddInfoDto.getPunishContent());
            //陈述申辩期
            dataMap.put("XZCFSXGZS_GZR", fastCaseAddInfoDto.getStatementPleadTerm());
            //联系电话
            dataMap.put("XZCFSXGZS_LXDH", fastCaseAddInfoDto.getFastTelephone());
            //联系地址
            dataMap.put("XZCFSXGZS_LXDZ", fastCaseAddInfoDto.getFastContactAddress());
            //违则详情
            dataMap.put("XZCFJDS_WZ", illegalDetailFormat);
            //罚则详情详情
            dataMap.put("XZCFSXGZS_GDTWO", punishDetailFormat);

        } else if (DocumentKindEnum.DOC_KIND_DK2BYXZCFGZS.getCode().equals(documentKindCode)) {

            dataMap.put("XZCFSXGZS__LARQ", caseRegisterTimeStr);
            dataMap.put("XZCFSXGZS_DSRMC", partyNames);
            //案由
            dataMap.put("XZCFSXGZS_AY", caseReasonNameSimple);
            //违法事实
            dataMap.put("XZCFSXGZS_WFSS", caseMainDetailInfo.getIllegalFact());
            //违则
            dataMap.put("XZCFSXGZS_FZ", illegalBasisFormat);
            //相关证据
            dataMap.put("XZCFSXGZS_XGZJ", caseMainDetailInfo.getRelateEvidence());
            //不予处罚原因
            dataMap.put("XZCFSXGZS_JY", caseMainDetailInfo.getNotGivePunishReason());
            //案由罚则
            dataMap.put("XZCFSXGZS_AYFZ", punishBasisFormat);
            //可输入责令等内容
            dataMap.put("chargeContent", "");
            //联系电话
            dataMap.put("XZCFSXGZS_LXDH", fastCaseAddInfoDto.getFastTelephone());
            //联系地址
            dataMap.put("XZCFSXGZS_LXDZ", fastCaseAddInfoDto.getFastContactAddress());
            //违则详情
            dataMap.put("XZCFJDS_WZ", illegalDetailFormat);
            //罚则详情
            dataMap.put("XZCFJDS_FZ", punishDetailFormat);
            //陈述、申辩天数
            dataMap.put("XZCFSXGZS_GZR", fastCaseAddInfoDto.getStatementPleadTerm());
            //联系人
            dataMap.put("XZCFSXGZS_LXR", handlePersonNames);
        }
    }

    /**
     * 描述：组装当事人信息
     *
     * @param caseId  用例id
     * @param dataMap 数据地图
     * @return {@link Map<String, Object> }
     * @author shishengyao
     * @date 2023/05/08
     */
    private Map<String, Object> dealAssembleDocumentPersonInfo(String caseId, Map<String, Object> dataMap) {
        CasePartiesQueryDto casePartiesQueryDto = new CasePartiesQueryDto();
        casePartiesQueryDto.setCaseId(caseId);
        casePartiesQueryDto.setDocumentPartyType(Constant.STRING_1);
        casePartiesQueryDto.setPartyType("1,2");
        List<Map<String, Object>> casePartiesDetailInfoList = casePartiesRecordService.getCasePartiesDetailInfoList(casePartiesQueryDto);
        if (ObjectUtil.isNotEmpty(casePartiesDetailInfoList)) {
            Map<String, Object> stringObjectMap = casePartiesDetailInfoList.get(0);
            String partyType = stringObjectMap.get("partyType").toString();
            if (PartyTypeEnum.PERSON.getCode().equals(partyType)) {
                dataMap.put("personInfoCycle", casePartiesDetailInfoList);
            } else {
                dataMap.put("legalInfoCycle", casePartiesDetailInfoList);
            }
        }
        return dataMap;
    }

    /**
     * 交易组合文档处理的人
     *
     * @param caseHandlePersonRecordList 案件处理人记录列表
     * @param dataMap                    数据地图
     * @return {@link Map<String, Object> }
     * @author shishengyao
     * @date 2023/05/08
     */
    private Map<String, Object> dealAssembleDocumentHandlePerson(List<CaseHandlePersonRecord> caseHandlePersonRecordList, Map<String, Object> dataMap) {
        //主办人、承办人签名
        String mainHandleSignPic = Constant.DOC_MAIN_HANDLE_SIGN_PIC;
        String assistHandleSignPic = Constant.DOC_ASSIST_HANDLE_SIGN_PIC;
        caseHandlePersonRecordList.forEach(e -> {
            if (HandlePersonTypeEnum.MAIN.getCode().equals(e.getHandlePersonType())) {
                dataMap.put(mainHandleSignPic, e.getHandleSignPic());
            } else if (HandlePersonTypeEnum.ASSIST.getCode().equals(e.getHandlePersonType())) {
                dataMap.put(assistHandleSignPic, e.getHandleSignPic());
            }
        });
        return dataMap;
    }


    public void generateExecuteConditionAutomaticRecord(FastCaseAutoEndSaveDto saveDto, CaseMainDetailInfo caseMainDetailInfo, List<CaseHandlePersonRecord> caseHandlePersonRecordList) {
        HashMap<String, Object> dataMap = new HashMap<>(20);
        StageDocCommonOperateSaveDto commonOperateSaveDto = new StageDocCommonOperateSaveDto();
        String caseId = saveDto.getCaseId();
        List<CasePartiesRecordVo> casePartiesInfo = casePartiesRecordService.getCasePartiesInfo(saveDto.getCaseId());
        String partyName = casePartiesInfo.get(0).getPartyName();
        String partyId = casePartiesInfo.get(0).getPartyId();

        //获取案件信息
        LocalDate executeFinishDate = caseMainDetailInfo.getExecuteFinishDate();
        executeFinishDate = ObjectUtils.isEmpty(executeFinishDate) ? LocalDate.now() : executeFinishDate;
        String executeFinishDateStr = executeFinishDate.format(DateTimeFormatter.ofPattern("yyyy年M月d日"));
        String punishKind = caseMainDetailInfo.getPunishKinds();
        //获取办案人员
        String mainHandlerName = "";
        String assistHandlerName = "";
        String mainHandlerCert = "";
        String assistHandlerCert = "";
        for (CaseHandlePersonRecord handler : caseHandlePersonRecordList) {
            String handlePersonType = handler.getHandlePersonType();
            if (Constant.STRING_1.equals(handlePersonType)) {
                //主办
                mainHandlerName = handler.getHandlePersonName();
                mainHandlerCert = handler.getLawEnforcementCert();
            } else {
                //协办
                assistHandlerName = handler.getHandlePersonName();
                assistHandlerCert = handler.getLawEnforcementCert();
            }
            if (!ObjectUtils.isEmpty(mainHandlerName) && !ObjectUtils.isEmpty(assistHandlerName)) {
                break;
            }
        }
        String documentCatalogCode = "";
        if (Constant.STRING_1.equals(caseMainDetailInfo.getInvestConclusion()) && punishKind.contains("罚款")) {
            documentCatalogCode = Constant.STRING_DOCUMENT_CATALOG_CODE_AUTO_ZXQKJL;
            //执行完成日期
            dataMap.put("ZXQKJL_AUTO_ZXWCRQ", executeFinishDateStr);
            //获取宽表信息

            executeFinishDate = caseMainDetailInfo.getExecuteFinishDate();
            if (ObjectUtils.isEmpty(caseMainDetailInfo)) {
                throw new com.icinfo.cloud.provider.common.exception.BusinessException("未匹配到案件详情-caseId：" + caseId);
            }
            //执行方式
            String executeWay = caseMainDetailInfo.getExecuteWay();
            dataMap.put("ZXQKJL_AUTO_ZXFS", executeWay);
            //执行情况描述
            String executeConditionDesc = caseMainDetailInfo.getExecuteConditionDesc();
            dataMap.put("ZXQKJL_AUTO_ZXJCQK", executeConditionDesc);
            String documentNumber = caseMainDetailInfo.getPunishDocumentNumber();
            dataMap.put("ZXQKJL_AUTO_BZ", documentNumber);
            dataMap.put("ZXQKJL_AUTO_DSR", partyName);
            //获取缴款结果信息
            CasePaymentResultRecordVo resultInfo = casePaymentResultRecordService.getCasePaymentResultRecordDetailByCaseId(caseId);
            //缴款单号
            String noticeNo = resultInfo.getNoticeNo();
            dataMap.put("ZXQKJL_AUTO_JKDH", noticeNo);
            //缴款日期
            dataMap.put("ZXQKJL_AUTO_JKRQ", resultInfo.getPayDate());
            //缴款凭证号
            dataMap.put("ZXQKJL_AUTO_JKPZH", resultInfo.getCertificateNo());
            //缴款凭证校验码
            dataMap.put("ZXQKJL_AUTO_JKPZJYM", resultInfo.getCheckCode());
            //代收机构	ZXQKJL_AUTO_DSJG
            dataMap.put("ZXQKJL_AUTO_DSJG", resultInfo.getTradeName());
            //支付方式	ZXQKJL_AUTO_ZFFS
            dataMap.put("ZXQKJL_AUTO_ZFFS", resultInfo.getWayName());

            //查询缴费项目明细表
            CasePaymentMainRecordQueryDto queryPaymentMain = new CasePaymentMainRecordQueryDto();
            queryPaymentMain.setCaseId(caseId);
            queryPaymentMain.setNoticeNo(noticeNo);
            List<CasePaymentMainRecordVo> list = casePaymentMainRecordService.getPaymentChannelConfigInfo(queryPaymentMain);
            if (!ObjectUtils.isEmpty(list) && list.size() > 0) {
                CasePaymentMainRecordVo casePaymentMainRecord = list.get(Constant.INTEGER_0);
                //查询缴款主要信息记录表的主键id
                String paymentId = casePaymentMainRecord.getId();
                CasePaymentItemDetailQueryDto queryDto = new CasePaymentItemDetailQueryDto();
                queryDto.setPaymentId(paymentId);
                List<CasePaymentItemDetailVo> itemList = casePaymentItemDetailService.getCasePaymentItemDetailInfo(queryDto);
                if (!ObjectUtils.isEmpty(itemList) && itemList.size() > 0) {
                    //目前只取一条
                    CasePaymentItemDetailVo itemInfo = itemList.get(Constant.INTEGER_0);
                    //项目编码	ZXQKJL_AUTO_XMBM
                    dataMap.put("ZXQKJL_AUTO_XMBM", itemInfo.getChitCode());
                    //项目名称	ZXQKJL_AUTO_XMMC
                    dataMap.put("ZXQKJL_AUTO_XMMC", itemInfo.getChitName());
                    //证据描述-单位	ZXQKJL_AUTO_ZJMS_DW
                    dataMap.put("ZXQKJL_AUTO_ZJMS_DW", itemInfo.getMetricUnit());
                    //证据描述-数量	ZXQKJL_AUTO_ZJMS_SL
                    dataMap.put("ZXQKJL_AUTO_ZJMS_SL", itemInfo.getChCount());
                    //证据描述-标准	ZXQKJL_AUTO_ZJMS_STANDARD
                    dataMap.put("ZXQKJL_AUTO_ZJMS_STANDARD", itemInfo.getChargeStandard());
                    //证据描述-金额	ZXQKJL_AUTO_ZJMS_JE
                    dataMap.put("ZXQKJL_AUTO_ZJMS_JE", itemInfo.getChMoney());
                    //证据描述-备注	ZXQKJL_AUTO_ZJMS_BZ
                    dataMap.put("ZXQKJL_AUTO_ZJMS_BZ", "");
                }
            }
            //证据原件	ZXQKJL_AUTO_ZJYJ
            List<Object> zjyjList = new ArrayList<>();
            CaseAttachmentInfoQueryDto queryAttach = new CaseAttachmentInfoQueryDto();
            queryAttach.setCaseId(caseId);
            queryAttach.setDocumentCatalogCode(documentCatalogCode);
            queryAttach.setAttachmentTypeId(AttachmentTypeEnum.PAYMENT_PROOF.getCode());
            //获取附件信息
            List<CaseAttachmentInfoVo> paymentProofFileList = caseAppendixRecordService.getCaseAttachmentInfoList(queryAttach);
            if (!ObjectUtils.isEmpty(paymentProofFileList) && paymentProofFileList.size() > 0) {
                Map<String, String> zjyjMap = new HashMap<>(20);
                paymentProofFileList.forEach(e -> {
                    //将电子发票转换为图片
                    String imageBase64 = PdfUtil.pdfTransImage(e.getAppendixUrl());
                    zjyjMap.put("ZXQKJL_AUTO_ZJYJ", imageBase64);
                    zjyjList.add(zjyjMap);
                    //添加电子发票附件
                });
            }
//            dataMap.put("ZJYJ_AUTO_LIST", zjyjList);
            dataMap.put("ZXQKJL_AUTO_ZBRYXM", mainHandlerName);
            dataMap.put("ZXQKJL_AUTO_ZBRYZFZH", mainHandlerCert);
            dataMap.put("ZXQKJL_AUTO_XBRYXM", assistHandlerName);
            dataMap.put("ZXQKJL_AUTO_XBRYZFZH", assistHandlerCert);
        } else {
            documentCatalogCode = Constant.STRING_DOCUMENT_CATALOG_CODE_SDZX_ZXQKJL;
            // 行政处理-执行情况核查记录文书编码为“ZXQKHCJL29F4F”
            if (Constant.STRING_2.equals(caseMainDetailInfo.getHandleConclusion())) {
                documentCatalogCode = Constant.STRING_DOCUMENT_CATALOG_CODE_XZCL_ZXQKJL;
            }
            CaseMainInfoVo caseMainInfoVo = caseMainInfoService.getCaseMainInfo(caseId);
            SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(caseMainInfoVo.getCaseOrgCode(), caseMainInfoVo.getCaseDeptCode());
            //机构名称
            dataMap.put("ZXQKJL_AUTO_JGMC", sysDepartParam.getOrgStandardName());
            //当事人
            dataMap.put("ZXQKJL_DSR", partyName);
            //执行完成日期
            dataMap.put("ZXQKJL_ZXWCRQ", executeFinishDateStr);

            //执行情况描述
            String executeConditionDesc = caseMainDetailInfo.getExecuteConditionDesc();
            dataMap.put("ZXQKJL_ZXJCQK", executeConditionDesc);
            //执行方式
            String executeWay = caseMainDetailInfo.getExecuteWay();
            dataMap.put("ZXQKJL_ZXFS", executeWay);

            String documentNumber = caseMainDetailInfo.getPunishDocumentNumber();
            dataMap.put("ZXQKJL_BZ", documentNumber);
            dataMap.put("ZXQKJL_ZBRYXM", mainHandlerName);
            dataMap.put("ZXQKJL_ZBRYZFZH", mainHandlerCert);
            dataMap.put("ZXQKJL_XBRYXM", assistHandlerName);
            dataMap.put("ZXQKJL_XBRYZFZH", assistHandlerCert);
        }

        commonOperateSaveDto.setCaseId(caseId);
        commonOperateSaveDto.setDocumentCatalogCode(documentCatalogCode);
        commonOperateSaveDto.setDataMap(dataMap);
        commonOperateSaveDto.setIsUpdateRelationTable(YesOrNoEnum.NO.getCode());
        commonOperateSaveDto.setPartyId(partyId);
        commonOperateSaveDto.setCloseSignal("CLOSE-TRIGGER-DOCCREATE");
        stageDocCommonOperateService.saveDocInfo(commonOperateSaveDto);
    }

    /**
     * 描述：生成结案报告文书
     *
     * @param saveDto 保存dto
     * @author shishengyao
     * @date 2023/08/24
     */
    public void generateEndReportDocument(CaseMainInfoVo caseMainInfo, CaseMainDetailInfo caseMainDetailInfo, List<CaseHandlePersonRecord> caseHandlePersonRecordList, FastCaseAutoEndSaveDto saveDto, ConfigBusiParamDocumentInfo configBusiParamDocumentInfo) {
        String caseId = saveDto.getCaseId();

        //配置表
        String documentCatalogCode = configBusiParamDocumentInfo.getDocumentCatalogCode();
        //当事人信息
        List<CasePartiesRecordVo> casePartiesInfo = casePartiesRecordService.getCasePartiesInfo(caseId);
        String partyId = casePartiesInfo.stream().map(CasePartiesRecordVo::getPartyId).collect(Collectors.joining(","));

        // 1、查询是否有文书
        CaseDocumentRecord oldRecordInfo = caseDocumentRecordService.getCaseDocumentRecord(caseId, documentCatalogCode);
        Map<String, Object> paramMap;
        //存在历史数据，更新历史数据
        if (ObjectUtil.isNotEmpty(oldRecordInfo) && ObjectUtil.isNotEmpty(oldRecordInfo.getDocumentContent())) {
            String documentContent = oldRecordInfo.getDocumentContent();
            paramMap = JSON.parseObject(documentContent);
        } else {
            StageDocCommonHtmlRequest htmlRequest = new StageDocCommonHtmlRequest();
            htmlRequest.setCaseId(caseId);
            htmlRequest.setDocumentCatalogCode(configBusiParamDocumentInfo.getDocumentCatalogCode());
            DocumentCommonFormDataVo dataVo = stageDocCommonOperateService.getCommonDocumentFormData(htmlRequest);
            paramMap = dataVo.getDataMap();

        }
        //组装初始化文书参数
        //处罚告知审批表或不予处罚告知审批表
        //案件名称
        paramMap.put("case_name", caseMainInfo.getCaseName());
        //立案案号
        paramMap.put("AJJABG_AY", caseMainInfo.getCaseNumber());
        //案发时间
        paramMap.put("AJJABG_AFSJ", caseMainDetailInfo.getCaseHappenTime().format(DateTimeFormatter.ofPattern("yyyy年M月d日")));
        //案件来源
        paramMap.put("AJJABG_AJLY", caseMainInfo.getCaseSource());
        //结案时间
        paramMap.put("AJJABG_JARQ", LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy年M月d日")));
        List<Map> documentInfoList = new ArrayList<>();
        Map documentInfoMap = new HashMap();
        //行政处理文书文号
        CaseDocumentRecordCommonQueryDto commonQueryDto = new CaseDocumentRecordCommonQueryDto();
        commonQueryDto.setCaseId(caseId);
        commonQueryDto.setPartyId(partyId);
        commonQueryDto.setIsPunishDocument(Constant.STRING_1);
        List<CaseDocumentRecordDetailVo> caseDocumentRecordList = caseDocumentRecordService.getCaseDocumentRecordDocNumberInfoList(commonQueryDto);
        for (CaseDocumentRecordDetailVo detailVo : caseDocumentRecordList) {
            //行政处理文书文号
            documentInfoMap.put("AJJABG_XZCFWH", detailVo.getDocumentNumber());
            //送达时间
            documentInfoMap.put("AJJABG_SDSJ", detailVo.getSentTime());
        }
        documentInfoList.add(documentInfoMap);

        paramMap.put("documentInfoList", documentInfoList);


        //案件简要情况
        paramMap.put("AJJABG_AJJYQK", caseMainDetailInfo.getCaseConciseCondition());
        //执行方式
        paramMap.put("AJJABG_ZXFS", caseMainDetailInfo.getExecuteWay());

        //办案人员信息
        paramMap = dealAssembleDocumentHandlePerson(caseHandlePersonRecordList, paramMap);
        //当事人信息
        paramMap = dealAssembleDocumentPersonInfo(caseId, paramMap);

        //3、生成文书
        StageDocCommonOperateSaveDto commonOperateSaveDto = new StageDocCommonOperateSaveDto();
        commonOperateSaveDto.setCaseId(caseId);
        commonOperateSaveDto.setDocumentCatalogCode(documentCatalogCode);
        commonOperateSaveDto.setDataMap(JSON.parseObject(JSONObject.toJSONString(paramMap), HashMap.class));
        commonOperateSaveDto.setIsUpdateRelationTable(YesOrNoEnum.NO.getCode());
        commonOperateSaveDto.setPartyId(partyId);
        stageDocCommonOperateService.saveDocInfo(commonOperateSaveDto);
    }
}
